<?php 
if (!defined('BASEPATH')){
	exit('No direct script access allowed');
}

/**
 * Voucher Controller
 * Build by Phuc Nguyen
 * Contact : nguyenvanphuc0626@gmail.com
 */

class Voucher extends BACKEND_Controller {

	public function __construct() {
		parent::__construct();
		$this->load->language('voucher');
		$this->load->language('button');
		if($this->database_connect_status){
			$this->load->model('voucher_model');
			$this->set_controller('voucher');
			$this->set_model($this->voucher_model);
		}
                $this->load->model('voucherPaymentLog_model');
                $this->load->model('voucherTicket_model');
                $this->load->model('voucherBank_model');
                $this->load->model('voucherOffice_model');
                $this->load->model('voucherDebts_model');
                $this->load->model('booking_model');
                $this->load->library('bookinglib');
                $this->bookinglib = new bookinglib();
	}
        
        public function check(){
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                        $this->view_data["voucher"]                                   = new stdClass();
                        $this->view_data["voucher"]->surplus                          = $this->input->post('surplus_fake');
                        $this->view_data["voucher"]->residual                         = $this->input->post('residual_fake');
                        $this->view_data["voucher"]->real_fare                        = $this->input->post('real_fare_fake');
                        $this->view_data["voucher"]->note_pay                         = $this->input->post('note_pay');
                        $this->view_data["voucher"]->payment_confirm                  = 1;
                        $this->view_data["voucher"]->clause                           = $this->input->post('clause_fake');
                        $this->view_data["voucher"]->checkbox_khautru                 = $this->input->post('checkbox_khautru_fake');
                        $this->view_data["voucher"]->checkbox_sodukh                  = $this->input->post('checkbox_sodukh_fake');
                        $this->view_data["voucher"]->ticketworkers                    = $this->input->post('ticketworkers');
                        //$this->view_data["voucher"]->lastupdated                      = date("Y-m-d H:i:s",time());

                        $this->load->helper('character');
                        $this->load->helper('form');
                        $this->load->library('form_validation');
                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $rules = array(
                            array(
                                'field'   => 'real_fare',
                                'label'   =>  $this->lang->line('real_fare'),
                                'rules'   => 'required|xss_clean'
                            ),array(
                                'field'   => 'clause',
                                'label'   =>  $this->lang->line('clause'),
                                'rules'   => 'required|max_length[255]|xss_clean'
                            ),array(
                                'field'   => 'note_pay',
                                'label'   =>  $this->lang->line('note'),
                                'rules'   => 'max_length[255]|xss_clean'
                            )
                        );
                        
                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $this->form_validation->set_rules($rules);

                        if ($this->form_validation->run()==TRUE){
                                $real_fare = $this->view_data["voucher"]->real_fare;
                                
                                if($this->view_data["voucher"]->checkbox_khautru == 1 || $this->view_data["voucher"]->checkbox_sodukh == 1){
                                    $this->voucher_model->updateSurplusAllCus(array('customerID'=>$this->input->post('customerID'),'residual'=>$this->input->post('residual_fake'),'owner'=>$this->input->post('owner')));
                                    if($this->input->post('net_fare_fake') < 0){
                                        $real_fare = 0 - $this->input->post('sale_fare_fake');
                                    } else {
                                        $real_fare = $this->input->post('sale_fare_fake');
                                    }
                                }
                                
                                $this->voucher_model->update($this->view_data["voucher"], $this->input->post('id'));
                                $this->checkResidual($this->input->post('id'),$this->input->post('residual_fake'));
                                
                                $data = array(
                                    'id'        =>  $this->input->post('id'),
                                    'surplus'   =>  $this->view_data["voucher"]->surplus,
                                    'amount'    =>  $real_fare,
                                    'residual'  =>  $this->view_data["voucher"]->residual,
                                    'note'      =>  $this->view_data["voucher"]->note_pay
                                );
                                $this->xulidata($data);
                                //admin log
				$this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                                $paramAdminLog  = array(
                                    'userid'            => $this->session->userdata['user_id'],
                                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                    'ip'                => $_SERVER['REMOTE_ADDR'],
                                    'logAction'         => '[UpdateVoucherPayment] '.$this->lang->line('update_voucher_success').' - ID:'.$this->input->post('id'),
                                    'agent_code'        => $this->session->userdata['agent_code']
                                );
                                $this->user_model->insertUserAdminLog($paramAdminLog);
                                echo '<script>window.top.location.href="/auth/voucher/";</script>';exit; 
                        }
            }
            
            if($this->input->get('id')){
                $info                           = $this->voucher_model->find_by(array('id'=>$this->input->get('id')));
                $this->statusVoucher($info);
                $info[0]->pnr                   =   $this->splitPnr($info[0]);
				
                switch($info[0]->payment_method){
                        case '4':
                            $data = $this->voucher_model->getInfoTable(array('voucher_id'=>$info[0]->id),'book_voucher_debts'); 
                            $info[0]->note_bk .= "\nLí do xin công nợ: ".$data[0]->reason."\nHạn thanh toán:".date("d-m-Y",$data[0]->debts);
                            break;
                        case '3':
                            $data = $this->voucher_model->getInfoTable(array('voucher_id'=>$info[0]->id),'book_voucher_bank'); 
                            $_data = $this->voucher_model->getInfoTable(array('bankid'=>$data[0]->bankid),'book_bank');

                            $info[0]->note_bk .= "\nNgân hàng: ".$_data[0]->bank_name;
                            break;
                }
                $list   =   $this->voucher_model->getListClause();
                foreach($list as $keys => $values){
                    $arr_complete[] = array(
                        'label' =>  $values->title,
                        'value' =>  $values->title,
                        'code'  =>  $values->code
                    );
                }
                $this->view_data['info']                    =   $info[0];
                $this->view_data['arr_complete']           =   json_encode($arr_complete);
                $this->load->view('auth/voucher/check', $this->view_data);
            }
        }
        
        private function splitPnr($list){
                $airline                        = json_decode($list->airline);
                $booking_place_code             = json_decode($list->booking_place_code);
                $pnr                            = '';
                foreach($booking_place_code as $key => $vals){
                    if($key < count($booking_place_code)-1){
                        $etc = ', ';
                    } else {
                        $etc = '';
                    }
                    $pnr .= $vals.'-'.$airline[$key].$etc;
                }
                return $pnr;
        }

        public function getInfoBookingHold(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                if($this->input->post('booking_types') == 1){//có nghĩa là nếu code là vé mới thì mới kiểm tra sự tồn tại code đó trong table voucher
                    $checkInfo  =   $this->voucher_model->selectVoucher($this->input->post('airline'),$this->input->post('booking_place_code'),$this->input->post('customerID'),$this->session->userdata['user_id']);
                    if($checkInfo){
                        $data = array(
                            'error'     =>  2,//code đã tồn tại trong he thong doi voi kh ...
                            'msg'       => json_encode($checkInfo[0])
                        );
                        die(json_encode($data));
                    }
                }

                $info = $this->voucher_model->getInfoBookingHold(NULL,$this->input->post('airline'),$this->input->post('booking_place_code'),$this->input->post('customerID'),$this->session->userdata['user_id'],$this->input->post('booking_types'));
                if(empty($info)){
                    $data = array(
                        'error'     =>  1,//code chưa khởi tạo booking
                        'msg'       =>  'Not found'
                    );
                    die(json_encode($data));
                } else {
                    $data = array(
                        'error'     =>  0,//0 ko loi
                        'msg'       =>  json_encode($info[0])
                    );
                    die(json_encode($data));
                }
            }
            die("0");
        }

        public function getContactFromPhone(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->load->model('listcustomers_model');
                $info = $this->listcustomers_model->searchCustomers(NULL,$this->input->post('phone'));
                if(empty($info)){
                    die("0");
                } else {
                    die(json_encode($info[0]));
                }
            }
            die("0");
        }
        
        public function getInfoAirCode(){
            $this->view_data['add']         =   $this->input->post('add');
            $this->load->view('auth/voucher/getInfoAirCode', $this->view_data);
        }

        public function updateVoucher($params){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                        $this->view_data["voucher"]                                     = new stdClass();
                        $this->view_data["voucher"]->phone                              = $this->input->post('phone');
                        $this->view_data["voucher"]->customerID                         = $this->input->post('customerID');
                        $this->view_data["voucher"]->airline                            = json_encode($this->input->post('airline'));
                        $this->view_data["voucher"]->booking_place_code                 = json_encode($this->input->post('booking_place_code'));
                        $this->view_data["voucher"]->booking_types                      = json_encode($this->input->post('booking_types'));
                        $this->view_data["voucher"]->createdTime                        = json_encode($this->input->post('createdTime'));
                        $this->view_data["voucher"]->net                                = json_encode($this->input->post('net_fare_fake'));
                        $this->view_data["voucher"]->sale                               = json_encode($this->input->post('sale_fare_fake'));
                        
                        $this->view_data["voucher"]->net_fare                         = ($this->input->post('sumNet_fake'))?$this->input->post('sumNet_fake'):'0';
                        $this->view_data["voucher"]->sale_fare                        = ($this->input->post('sumSale_fake'))?$this->input->post('sumSale_fake'):'0';
                        $this->view_data["voucher"]->note_bk                          = $this->input->post('note_bk');
                        $this->view_data["voucher"]->payment_method                   = $this->input->post('payment_method');
                        $this->view_data["voucher"]->owner                            = $this->session->userdata['user_id'];
                        $this->view_data["voucher"]->agent_code                       = $this->session->userdata['agent_code'];
                        $this->view_data["voucher"]->lastupdated                      = date("Y-m-d H:i:s",time());

                        $this->load->helper('character');
                        $this->load->helper('form');
                        $this->load->library('form_validation');
                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $rules = array(
                            array(
                                'field'   => 'phone',
                                'label'   =>  $this->lang->line('phone'),
                                'rules'   => 'required|numberic|xss_clean'
                            )
                            ,array(
                                'field'   => 'note_bk',
                                'label'   =>  $this->lang->line('note_bk'),
                                'rules'   => 'trim|max_length[255]|xss_clean'
                            )
                        );

                        $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                        $this->form_validation->set_rules($rules);

                        if ($this->form_validation->run()==TRUE){
                                if($params){
                                        //edit data
                                        unset($this->view_data["voucher"]->owner);
                                        unset($this->view_data["voucher"]->agent_code);
                                        unset($this->view_data["voucher"]->lastupdated);
					$this->voucher_model->update($this->view_data["voucher"], $params);
                                        
                                        $airline        = $this->input->post('airline');
                                        $createdTime    = $this->input->post('createdTime');

                                        foreach($this->input->post('booking_place_code') as $key => $vals){
                                            $booking_info                                                       =   $this->booking_model->find_by(array('booking_place_code'=>$vals,'airline'=>$airline[$key],'createdTime'=>$createdTime[$key]));
                                            $this->view_data["booking_voucher"]                                 =   new stdClass();
                                            $this->view_data["booking_voucher"]->voucher_id                     =   $params;
                                            $this->view_data["booking_voucher"]->payment_method                 =   $this->input->post('payment_method');
                                            $this->booking_model->update($this->view_data["booking_voucher"], $booking_info[0]->id);
                                            unset($this->view_data["booking_voucher"]);
                                            unset($booking_info);
                                        }
                                        
                                        $logAction                                          = '[UpdateVoucher] '.$this->lang->line('update_voucher_success').' - Chứng từ số '.$params;
				}else{
                                        //xu li cong doan cac Phuong phap thanh toan
                                            $params         = $this->voucher_model->create($this->view_data["voucher"]);
                                            $airline        = $this->input->post('airline');
                                            $createdTime    = $this->input->post('createdTime');
                                            
                                            foreach($this->input->post('booking_place_code') as $key => $vals){
                                                $booking_info                                                       =   $this->booking_model->find_by(array('booking_place_code'=>$vals,'airline'=>$airline[$key],'createdTime'=>$createdTime[$key]));
                                                $this->view_data["booking_voucher"]                                 =   new stdClass();
                                                $this->view_data["booking_voucher"]->voucher_id                     =   $params;
                                                $this->view_data["booking_voucher"]->payment_method                 =   $this->input->post('payment_method');
                                                $this->booking_model->update($this->view_data["booking_voucher"], $booking_info[0]->id);
                                                unset($this->view_data["booking_voucher"]);
                                                unset($booking_info);
                                            }
                                            
                                            //update table payment voucher
                                            $logAction = '[AddVoucher] '.$this->lang->line('add_voucher_success').' - Chứng từ số '.$params;
				}
                                
                                //----------------
                                $payment_i = true;
                                if($this->input->post('payment_method_fake') == $this->input->post('payment_method')){
                                        //update table ticket
                                        if($this->input->post('payment_method') == 2){
                                                $fake_Ticket    = $this->voucherTicket_model->find_by(array('voucher_id'=>$params));
                                                if($fake_Ticket){
                                                            if($this->input->post('ticket_phone') != '' 
                                                                    || $this->input->post('ticket_address') != ''
                                                                    || $this->input->post('ticket_province') != ''
                                                                    || $this->input->post('ticket_note') != ''){

                                                                    $this->view_data["fake_Ticket"]                  = new stdClass();
                                                                    $this->view_data["fake_Ticket"]->phone           = $ticket_phone;
                                                                    $this->view_data["fake_Ticket"]->address         = $ticket_address;
                                                                    $this->view_data["fake_Ticket"]->province        = $ticket_province;
                                                                    $this->view_data["fake_Ticket"]->note            = $ticket_note;

                                                                    $this->voucherTicket_model->update($this->view_data["fake_Ticket"],$fake_Ticket[0]->id);
                                                                    unset($fake_Ticket);unset($this->view_data["fake_Ticket"]);
                                                            }
                                                } else {
                                                            $this->view_data["u_voucher_ticket"]                        =   new stdClass();
                                                            $this->view_data["u_voucher_ticket"]->customerID            =   $this->input->post('customerID');
                                                            $this->view_data["u_voucher_ticket"]->voucher_id            =   $params;
                                                            $this->view_data["u_voucher_ticket"]->phone                 =   $this->input->post('ticket_phone');
                                                            $this->view_data["u_voucher_ticket"]->address               =   $this->input->post('ticket_address');
                                                            $this->view_data["u_voucher_ticket"]->province              =   $this->input->post('ticket_province');
                                                            $this->view_data["u_voucher_ticket"]->note                  =   $this->input->post('ticket_note');

                                                            $this->view_data["u_voucher_ticket"]->owner                 =   $this->session->userdata['user_id'];
                                                            $this->view_data["u_voucher_ticket"]->agent_code            =   $this->session->userdata['agent_code'];
                                                            $this->view_data["u_voucher_ticket"]->lastupdated           =   date("Y-m-d H:i:s",time());

                                                            $this->voucherTicket_model->create($this->view_data["u_voucher_ticket"]);
                                                            unset($this->view_data["u_voucher_ticket"]);
                                                }
                                        }
                                        //update table ngan hang
                                        if($this->input->post('payment_method') == 3){
                                                $fake_Bank  = $this->voucherBank_model->find_by(array('voucher_id'=>$params));
                                                if($fake_Bank){
                                                        if($this->input->post('choicebank')!=''){
                                                            $this->view_data["fake_Bank"]                   = new stdClass();
                                                            $this->view_data["fake_Bank"]->bankid           = $this->input->post('choicebank');

                                                            $this->voucherBank_model->update($this->view_data["fake_Bank"],$fake_Bank[0]->id);
                                                            unset($fake_Bank);unset($this->view_data["fake_Bank"]);
                                                        }
                                                } else {
                                                        $this->view_data["u_voucher_bank"]                          =   new stdClass();
                                                        $this->view_data["u_voucher_bank"]->customerID              =   $this->input->post('customerID');
                                                        $this->view_data["u_voucher_bank"]->voucher_id              =   $params;
                                                        $this->view_data["u_voucher_bank"]->bankid                  =   $this->input->post('choicebank');

                                                        $this->view_data["u_voucher_bank"]->owner                   =   $this->session->userdata['user_id'];
                                                        $this->view_data["u_voucher_bank"]->agent_code              =   $this->session->userdata['agent_code'];
                                                        $this->view_data["u_voucher_bank"]->lastupdated             =   time();

                                                        $this->load->model('voucherBank_model');
                                                        $this->voucherBank_model->create($this->view_data["u_voucher_bank"]);
                                                        unset($this->view_data["u_voucher_bank"]);
                                                }
                                        }
                                        //update table cong nợ
                                        if($this->input->post('payment_method') == 4){
                                                $fake_Debts = $this->voucherDebts_model->find_by(array('voucher_id'=>$params));
                                                if($fake_Debts){
                                                        if($this->input->post('reason') != '' || $this->input->post('maturity') != ''){
                                                            $this->view_data["fake_Debts"]                      = new stdClass();
                                                            $this->view_data["fake_Debts"]->reason              = $this->input->post('reason');
                                                            $this->view_data["fake_Debts"]->debts               = strtotime($this->input->post('maturity'));
                                                            $this->voucherDebts_model->update($this->view_data["fake_Debts"],$fake_Debts[0]->id);
                                                            unset($fake_Debts);unset($this->view_data["fake_Debts"]);
                                                        }
                                                } else {
                                                        $this->view_data["u_voucher_debts"]                          =   new stdClass();
                                                        $this->view_data["u_voucher_debts"]->customerID              =   $this->input->post('customerID');
                                                        $this->view_data["u_voucher_debts"]->voucher_id              =   $params;
                                                        $this->view_data["u_voucher_debts"]->reason                  =   $this->input->post('reason');
                                                        $this->view_data["u_voucher_debts"]->debts                   =   strtotime($this->input->post('maturity'));

                                                        $this->view_data["u_voucher_debts"]->owner                   =   $this->session->userdata['user_id'];
                                                        $this->view_data["u_voucher_debts"]->agent_code              =   $this->session->userdata['agent_code'];
                                                        $this->view_data["u_voucher_debts"]->lastupdated             =   time();

                                                        $this->load->model('voucherDebts_model');
                                                        $this->voucherDebts_model->create($this->view_data["u_voucher_debts"]);
                                                }
                                        }
                                        
                                        //update table tại văn phòng
                                        if($this->input->post('payment_method') == 5){
                                                $fake_AtOffice  = $this->voucherOffice_model->find_by(array('voucher_id'=>$params));
                                                if($fake_AtOffice){
                                                    $this->view_data["fake_AtOffice"]                      = new stdClass();
                                                    $this->view_data["fake_AtOffice"]->note                = $this->view_data["booking"]->note;

                                                    $this->voucherOffice_model->update($this->view_data["fake_AtOffice"],$fake_AtOffice[0]->id);
                                                    unset($fake_AtOffice);unset($this->view_data["fake_AtOffice"]);
                                                } else {
                                                    $this->view_data["u_voucher_office"]                          =   new stdClass();
                                                    $this->view_data["u_voucher_office"]->customerID              =   $this->input->post('customerID');
                                                    $this->view_data["u_voucher_office"]->voucher_id              =   $params;

                                                    $this->view_data["u_voucher_office"]->owner                   =   $this->session->userdata['user_id'];
                                                    $this->view_data["u_voucher_office"]->agent_code              =   $this->session->userdata['agent_code'];
                                                    $this->view_data["u_voucher_office"]->lastupdated             =   time();

                                                    $this->load->model('voucherOffice_model');
                                                    $this->voucherOffice_model->create($this->view_data["u_voucher_office"]);
                                                    unset($this->view_data["u_voucher_office"]);
                                                }
                                        }
                                        
                                        //end table
                                        
                                } else {
                                    //delele BOOKIGN CU
                                    if($this->uri->segment(4) == "edit"){
                                        switch ($this->input->post('payment_method_fake')){
                                            case '2':
                                                    $del = $this->voucherTicket_model->find_by(array('voucher_id'=>$params));
                                                    $this->voucherTicket_model->delete(array('id'=>$del[0]->id));									
                                               break;
                                            case '3':
                                                    $del = $this->voucherBank_model->find_by(array('voucher_id'=>$params));
                                                    $this->voucherBank_model->delete(array('id'=>$del[0]->id));									
                                               break;
                                            case '4':
                                                    $del = $this->voucherDebts_model->find_by(array('voucher_id'=>$params));
                                                    $this->voucherDebts_model->delete(array('id'=>$del[0]->id));
                                               break;
                                            case '5':
                                                    $del = $this->voucherOffice_model->find_by(array('voucher_id'=>$params));
                                                    $this->voucherOffice_model->delete(array('id'=>$del[0]->id));
                                               break;
                                        }
                                    }
                                    
                                    //khoi tao table moi
                                    switch ($this->input->post('payment_method')){
                                        case '2'://giao vé
                                            $this->view_data["u_voucher_ticket"]                        =   new stdClass();
                                            $this->view_data["u_voucher_ticket"]->customerID            =   $this->input->post('customerID');
                                            $this->view_data["u_voucher_ticket"]->voucher_id            =   $params;
                                            $this->view_data["u_voucher_ticket"]->phone                 =   $this->input->post('ticket_phone');
                                            $this->view_data["u_voucher_ticket"]->address               =   $this->input->post('ticket_address');
                                            $this->view_data["u_voucher_ticket"]->province              =   $this->input->post('ticket_province');
                                            $this->view_data["u_voucher_ticket"]->note                  =   $this->input->post('ticket_note');

                                            $this->view_data["u_voucher_ticket"]->owner                 =   $this->session->userdata['user_id'];
                                            $this->view_data["u_voucher_ticket"]->agent_code            =   $this->session->userdata['agent_code'];
                                            $this->view_data["u_voucher_ticket"]->lastupdated           =   date("Y-m-d H:i:s",time());

                                            $payment_i  =   $this->voucherTicket_model->create($this->view_data["u_voucher_ticket"]);
                                            unset($this->view_data["u_voucher_ticket"]);
                                            break;
                                        case '3':
                                            $this->view_data["u_voucher_bank"]                          =   new stdClass();
                                            $this->view_data["u_voucher_bank"]->customerID              =   $this->input->post('customerID');
                                            $this->view_data["u_voucher_bank"]->voucher_id              =   $params;
                                            $this->view_data["u_voucher_bank"]->bankid                  =   $this->input->post('choicebank');

                                            $this->view_data["u_voucher_bank"]->owner                   =   $this->session->userdata['user_id'];
                                            $this->view_data["u_voucher_bank"]->agent_code              =   $this->session->userdata['agent_code'];
                                            $this->view_data["u_voucher_bank"]->lastupdated             =   time();

                                            $payment_i  =   $this->voucherBank_model->create($this->view_data["u_voucher_bank"]);
                                            unset($this->view_data["u_voucher_bank"]);
                                            break;
                                        case '4':
                                            $this->view_data["u_voucher_debts"]                          =   new stdClass();
                                            $this->view_data["u_voucher_debts"]->customerID              =   $this->input->post('customerID');
                                            $this->view_data["u_voucher_debts"]->voucher_id              =   $params;
                                            $this->view_data["u_voucher_debts"]->reason                  =   $this->input->post('reason');
                                            $this->view_data["u_voucher_debts"]->debts                   =   strtotime($this->input->post('maturity'));

                                            $this->view_data["u_voucher_debts"]->owner                   =   $this->session->userdata['user_id'];
                                            $this->view_data["u_voucher_debts"]->agent_code              =   $this->session->userdata['agent_code'];
                                            $this->view_data["u_voucher_debts"]->lastupdated             =   time();

                                            $payment_i  =   $this->voucherDebts_model->create($this->view_data["u_voucher_debts"]);
                                            unset($this->view_data["u_voucher_debts"]);
                                        //con buoc 4
                                        case '5':
                                            $this->view_data["u_voucher_office"]                          =   new stdClass();
                                            $this->view_data["u_voucher_office"]->customerID              =   $this->input->post('customerID');
                                            $this->view_data["u_voucher_office"]->voucher_id              =   $params;

                                            $this->view_data["u_voucher_office"]->owner                   =   $this->session->userdata['user_id'];
                                            $this->view_data["u_voucher_office"]->agent_code              =   $this->session->userdata['agent_code'];
                                            $this->view_data["u_voucher_office"]->lastupdated             =   time();

                                            $payment_i  =   $this->voucherOffice_model->create($this->view_data["u_voucher_office"]);
                                            unset($this->view_data["u_voucher_office"]);
                                            break;
                                    }
                                }

                                if(!$payment_i){
                                        $paramAdminLog  = array(
                                            'userid'            => $this->session->userdata['user_id'],
                                            'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                            'ip'                => $_SERVER['REMOTE_ADDR'],
                                            'logAction'         => 'Không thể PTTT '.$this->input->post('payment_method').' cho ct='.$params,
                                            'agent_code'        => $this->session->userdata['agent_code']
                                        );
                                        $this->user_model->insertUserAdminLog($paramAdminLog);
                                        die("Có lỗi xảy ra khi bạn sửa nội dung CT! Vui lòng lien he Admin");
                                }
                                //----------------
                                
				if($params){
					$this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
					$paramAdminLog  = array(
                                            'userid'            => $this->session->userdata['user_id'],
                                            'lastLogin'         => date('Y-m-d :H:i:s',time()),
                                            'ip'                => $_SERVER['REMOTE_ADDR'],
                                            'logAction'         => $logAction,
                                            'agent_code'        => $this->session->userdata['agent_code']
                                        );
                                        $this->user_model->insertUserAdminLog($paramAdminLog);
                                        echo '<script>window.top.location.href="/auth/voucher/";</script>';exit;
				}
                        }
            }
        }


        protected function update($params=NULL){
            $this->updateVoucher($params);
            
            $this->load->model('voucher_model');
            $this->load->model('language_model');

            if(isset($params)){
                    $voucher_query	= $this->voucher_model->find_by(array('id'=>$params));
                    
                    if(!isset($voucher_query[0])){
                            $this->session->set_flashdata('flash_message', $this->lang->line('not_exists'));
                            redirect(site_url('auth/voucher'));
                            exit();
                    }
                    $booking_types                                      = json_decode($voucher_query[0]->booking_types);
                    $airline                                            = json_decode($voucher_query[0]->airline);
                    $booking_place_code                                 = json_decode($voucher_query[0]->booking_place_code);
                    $createdTime                                        = json_decode($voucher_query[0]->createdTime);
                    $net                                                = json_decode($voucher_query[0]->net);
                    $sale                                               = json_decode($voucher_query[0]->sale);
                    $i = 0;
                    while($i < count($airline)){
                        $booking_info[$i] = array(
                            'booking_types'         =>  $booking_types[$i],
                            'airline'               =>  $airline[$i],
                            'booking_place_code'    =>  $booking_place_code[$i],
                            'createdTime'           =>  $createdTime[$i],
                            'net'                   =>  $net[$i],
                            'sale'                  =>  $sale[$i],
                            'net_fake'              =>  number_format($net[$i],"0",",",",").' VNĐ',
                            'sale_fake'             =>  number_format($sale[$i],"0",",",",").' VNĐ'
                        );
                        $i++;
                    }
                    $voucher_query[0]->booking_info                     = $booking_info;
                    $this->view_data['voucher']				= $voucher_query[0];
            }

            $this->view_data['js'] = array(
                            base_url().'static/templates/backend/js/main.js'
            );
            $this->view_data['css'] = array(
            );
            $this->load->view('auth/voucher/edit', $this->view_data);
	}
        
        public function getContactsById(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $this->load->model('listcustomers_model');
                $info = $this->listcustomers_model->find_by(array('customerID'=>$this->input->post('customerID')));
                if($info){
                    die(($info[0]->voucher)?$info[0]->voucher:'0');
                } else {
                    die("-1");
                }
            }
        }
        
        public function receipt(){
            $this->bookinglib->direct();
            $this->load->model('configuration_model');
            $this->load->model('bookhistory_model');

            $info       = $this->voucher_model->find_by(array('id'=>$this->input->get('id')));
            
            $this->view_data['css']			= array(
				STATIC_URL.'backend/css/page.css',
		);
            
            $airline                        = json_decode($info[0]->airline);
            $booking_place_code             = json_decode($info[0]->booking_place_code);
            $pnr                            = '';
            foreach($booking_place_code as $key => $vals){
                if($key < count($booking_place_code)-1){
                    $etc = ', ';
                } else {
                    $etc = '';
                }
                $pnr .= $vals.'-'.$airline[$key].$etc;
            }
            
            $info[0]->booking_place_code                      = $pnr;
            $info[0]->real_fare                               = $info[0]->sale_fare;
            $info[0]->booking_id                              = $info[0]->id;
            $this->view_data['info']                          = $info[0];
            $this->view_data['configuration']                 = $this->configuration_model->find_by();
            
            $this->load->view('auth/bookhistory/receipt', $this->view_data);
        }
        
        public function xulidata($params){
            $info       = $this->voucher_model->find_by(array('id'=>$params['id']));
            
//            if($params['residual']>= 0){
                $pnr            = json_decode($info[0]->booking_place_code);
                $airline        = json_decode($info[0]->airline);
                $createdTime    = json_decode($info[0]->createdTime);
                
                foreach($pnr as $keys => $vals){
                    $booking_info       =       $this->booking_model->find_by(array('booking_place_code'=>$vals,'airline'=>$airline[$keys],'createdTime'=>$createdTime[$keys]));
                    $data = array(
                        'customerID'        =>      $booking_info[0]->customerID,
                        'booking_id'        =>      $booking_info[0]->id,
                        'amount'            =>      $params['amount']
                    );
                    $this->booking_model->udpate_confirm($data);
                }
//            }
            
            //update table log payment method
            switch($info[0]->payment_method){
                case '2'://giao vé
                    $this->view_data["voucherTicket"]                           = new stdClass();
                    $this->view_data["voucherTicket"]->surplus                  = $params['surplus'];
                    $this->view_data["voucherTicket"]->amount                   = $params['amount'];
                    $this->view_data["voucherTicket"]->residual                 = $params['residual'];
                    $this->view_data["voucherTicket"]->payment_confirm          = 1;
                    $this->view_data["voucherTicket"]->lastupdated              = time();
                    
                    $payment_info   = $this->voucherTicket_model->find_by(array('voucher_id' => $params['id']));
                    $this->voucherTicket_model->update($this->view_data["voucherTicket"],$payment_info[0]->id);
                    unset($this->view_data["voucherTicket"]);
                    break;
                case '3'://ngân hàng
                    $this->view_data["voucherBank"]                             = new stdClass();
                    $this->view_data["voucherBank"]->surplus                    = $params['surplus'];
                    $this->view_data["voucherBank"]->amount                     = $params['amount'];
                    $this->view_data["voucherBank"]->residual                   = $params['residual'];
                    $this->view_data["voucherBank"]->payment_confirm            = 1;
                    $this->view_data["voucherBank"]->lastupdated                = time();
                    
                    $payment_info   = $this->voucherBank_model->find_by(array('voucher_id' => $params['id']));
                    $this->voucherBank_model->update($this->view_data["voucherBank"],$payment_info[0]->id);                    
                    unset($this->view_data["voucherBank"]);
                    break;
                //con so 4
                case '4'://cong no
                    $this->view_data["voucherDebts"]                             = new stdClass();
                    $this->view_data["voucherDebts"]->surplus                    = $params['surplus'];
                    $this->view_data["voucherDebts"]->amount                     = $params['amount'];
                    $this->view_data["voucherDebts"]->residual                   = $params['residual'];
                    $this->view_data["voucherDebts"]->payment_confirm            = 1;
                    $this->view_data["voucherDebts"]->lastupdated                = time();
                    
                    $payment_info   = $this->voucherDebts_model->find_by(array('voucher_id' => $params['id']));
                    $this->voucherDebts_model->update($this->view_data["voucherDebts"],$payment_info[0]->id);                    
                    unset($this->view_data["voucherDebts"]);
                    break;
                //con so 4
                case '5'://tai van phong
                    $this->view_data["voucherOffice"]                             = new stdClass();
                    $this->view_data["voucherOffice"]->surplus                    = $params['surplus'];
                    $this->view_data["voucherOffice"]->amount                     = $params['amount'];
                    $this->view_data["voucherOffice"]->residual                   = $params['residual'];
                    $this->view_data["voucherOffice"]->payment_confirm            = 1;
                    $this->view_data["voucherOffice"]->lastupdated                = time();
                    
                    $payment_info   = $this->voucherOffice_model->find_by(array('voucher_id' => $params['id']));
                    $this->voucherOffice_model->update($this->view_data["voucherOffice"],$payment_info[0]->id);
                    unset($this->view_data["voucherOffice"]);
                    break;
            }
            
            //insert payment log
            $this->view_data["voucherPaymentLog"]                               = new stdClass();
            $this->view_data["voucherPaymentLog"]->customerID                   = $info[0]->customerID;
            $this->view_data["voucherPaymentLog"]->voucher_id                   = $info[0]->id;
            $this->view_data["voucherPaymentLog"]->amount                       = $params['amount'];
            $this->view_data["voucherPaymentLog"]->surplus                      = $params['surplus'];
            $this->view_data["voucherPaymentLog"]->residual                     = $params['residual'];
            $this->view_data["voucherPaymentLog"]->note                         = $params['note'];
            $this->view_data["voucherPaymentLog"]->agent_code                   = $this->session->userdata['agent_code'];
            $this->view_data["voucherPaymentLog"]->owner                        = $this->session->userdata['user_id'];
            $this->view_data["voucherPaymentLog"]->lastupdated                  = time();
            
            $this->voucherPaymentLog_model->create($this->view_data["voucherPaymentLog"]);
            unset($this->view_data["voucherPaymentLog"]);
        }
                
        public function transportTicket(){
            $this->bookinglib->direct();            
            $cid                                = $this->input->get('id');
            if(!$cid){
                $this->bookinglib->direct();
            }
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                    $this->view_data["voucher"]                           = new stdClass();
                    $this->view_data["voucher"]->province                 = $this->input->post('province');
                    $this->view_data["voucher"]->ticketWorkers            = $this->input->post('ticketWorkers');
                    $this->view_data["voucher"]->district                 = $this->input->post('district');
                    $this->view_data["voucher"]->agent_code               = $this->session->userdata['agent_code'];
                    $this->view_data["voucher"]->lastupdated              = time();

                    $this->load->helper('form');
                    $this->load->helper('character');
                    $this->load->helper('form');
                    $this->load->library('form_validation');
                    $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                    $rules = array(
                        array(
                            'field'   => 'ticketWorkers',
                            'label'   =>  $this->lang->line('ticketWorkers'),
                            'rules'   => 'required|numberic|max_length[3]|xss_clean'
                        )
                        ,array(
                            'field'   => 'district',
                            'label'   =>  $this->lang->line('district'),
                            'rules'   => 'required|trim|max_length[3]|xss_clean'
                        )
                    );
                    
                    $this->form_validation->set_error_delimiters('<div class="alert alert-error"><strong>'.$this->lang->line('error').': </strong>', '</div>');
                    $this->form_validation->set_rules($rules);
                    if ($this->form_validation->run()==TRUE){
                            $i = 1;
                            while($i++ < 3){
                                $result = $this->voucherTicket_model->update($this->view_data["voucher"],$this->input->post('voucherTicket_id'));
                                if($result == 1){
                                    break;
                                }
                            }
                            $this->session->set_flashdata('flash_message', $this->lang->line('update_successful'));
                            echo '<script>window.top.location.href="/auth/voucher/";</script>';exit;
                    } else {
                            $cid = $this->input->post('id');
                    }
            }            
            $info                               = $this->voucher_model->find_by(array('id' => $cid));
            $this->statusVoucher($info);
            $payment_info                       = $this->voucherTicket_model->find_by(array('voucher_id' => $info[0]->id));
            $this->statusVoucherMethod($payment_info,'notUseTicket');
            $province                           = $this->voucher_model->provinceById($payment_info[0]->province);
            
            $info[0]->payment_info              = $payment_info[0]->phone."\n".$payment_info[0]->address."\n".$province[0]->name;
            $info[0]->voucherTicket_id          = $payment_info[0]->id;
            
            $info[0]->ticketWorkers             = $payment_info[0]->ticketWorkers;
            $info[0]->district                  = $payment_info[0]->district;
            
            $this->view_data['css']             = array(STATIC_URL.'backend/css/page.css');
            $this->view_data['transportTicket'] = $info[0];
            
            $this->load->view('auth/voucher/transportTicket', $this->view_data);
        }
        
        private function statusVoucher($params){
            if(empty($params)){
                    $this->session->set_flashdata('flash_message', $this->lang->line('voucher_deleted'));
                    echo '<script>window.top.location.href="/auth/voucher/";</script>';exit;
            }
        }
        
        private function statusVoucherMethod($params,$translte){
            if(empty($params)){
                    $this->session->set_flashdata('flash_message', $this->lang->line($translte));
                    echo '<script>window.top.location.href="/auth/voucher/";</script>';exit;
            }
        }

        private function permissionVoucher($list){
            if(!in_array($this->session->userdata['user_id'],$list)){
                $this->session->set_flashdata('flash_message', $this->lang->line('access_denied'));
                echo '<script>window.top.location.href="/auth/voucher/";</script>';exit;
            }
        }
        
        public function approve(){
            $this->bookinglib->direct();            
            $cid                                = $this->input->get('id');
            if(!$cid){
                $this->bookinglib->direct();
            }
            
            $this->permissionVoucher(array('178'));
            
            if($this->input->server('REQUEST_METHOD')=='POST'){
                    $this->view_data["voucher"]                           = new stdClass();
                    $this->view_data["voucher"]->payment_confirm          = 1;
                    $this->view_data["voucher"]->lastupdated              = time();
                    
                    $i = 1;
                    while($i++ < 3){
                        $result = $this->voucherDebts_model->update($this->view_data["voucher"],$this->input->post('debts_id'));
                        if($result == 1){
                            break;
                        }
                    }
                    unset($i);
                    
                    $this->load->model('booking_model');
                    $this->load->model('bookhistory_model');
                    $this->view_data["bookhistory"]         = new stdClass();
                    
                    $booking    =   $this->booking_model->find_by(array('voucher_id'=>$this->input->post('voucher_id')));
                    foreach($booking as $keys => $vals){
                        $this->booking_model->delete(array('id'=>$vals->id));
                        
                        $ngay_dau_bay                                   =   json_decode($vals->booking);
                        $check                                          =   explode("-",$ngay_dau_bay[0]);
                        $this->view_data["bookhistory"]                 =   $vals;
                        $this->view_data["bookhistory"]->ngay_dau_bay   =   date("Y-m-d",strtotime(str_replace('/','-',$check[0])));
                        $this->view_data["bookhistory"]->booking_id     =   $vals->id;
                        $this->view_data["bookhistory"]->real_fare      =   $vals->sale_fare;
                        $this->view_data["bookhistory"]->payment_confirm = 1;
                        $this->view_data["bookhistory"]->payment_air    = 1;

                        if($vals->payment_method == 2 && $vals->booking_types == 1){
                            $agw                    = 0;
                            if(strpos($info[0]->booking,'AGW')){
                                $json_booking = json_decode($info[0]->booking);
                                foreach($json_booking as $keys => $values){
                                    if(strpos($values,'AGW')){
                                        $agw = $agw + 1;
                                    }
                                }
                            }
                           $this->view_data["bookhistory"]->segments      =   (count(json_decode($info[0]->booking)) - $agw) * count(explode("||", $info[0]->booking_customer_name));
                        }
                        
                        $this->view_data["bookhistory"]->id               =   'NULL';
                        $result = $this->bookhistory_model->create($this->view_data["bookhistory"]);
                        if(!$result){
                            die("Insert Booking History Fail! Contact Admin!");
                        }
                        unset($this->view_data["bookhistory"]);
                    }
                    
                    //insert payment log
                    $voucherInfo                                                        = $this->voucher_model->find_by(array('id'=>$this->input->post('voucher_id')));
                    $this->view_data["voucherPaymentLog"]                               = new stdClass();
                    $this->view_data["voucherPaymentLog"]->customerID                   = $voucherInfo[0]->customerID;
                    $this->view_data["voucherPaymentLog"]->voucher_id                   = $this->input->post('voucher_id');
                    $this->view_data["voucherPaymentLog"]->amount                       = $voucherInfo[0]->sale_fare;
                    $this->view_data["voucherPaymentLog"]->owner                        = $this->session->userdata['user_id'];
                    $this->view_data["voucherPaymentLog"]->lastupdated                  = time();

                    $this->voucherPaymentLog_model->create($this->view_data["voucherPaymentLog"]);
                    unset($this->view_data["voucherPaymentLog"]);
                    
                    die("0");
            }
            $info                               = $this->voucher_model->find_by(array('id' => $cid));
            $this->statusVoucher($info);
            $payment_info                       = $this->voucherDebts_model->find_by(array('voucher_id' => $info[0]->id));
            $this->statusVoucherMethod($payment_info,'notUseDebts');
            $payment_info[0]->net_fare              = $info[0]->net_fare;
            $payment_info[0]->sale_fare             = $info[0]->sale_fare;
            $payment_info[0]->booking_place_code    = $info[0]->booking_place_code;
            $this->view_data['approve']             = $payment_info[0];
            $this->load->view('auth/voucher/approve', $this->view_data);
        }
        
        private function checkResidual($params,$residual){
            if($residual < 0){
                
                $info1                                = $this->voucher_model->find_by(array('id'=>$params));
                $info1[0]->net_fare                   = $info1[0]->residual;
                $info1[0]->sale_fare                  = $info1[0]->residual;
                $info1[0]->real_fare                  = $info1[0]->residual;
                $info1[0]->lastupdated                = date("Y-m-d H:i:s");
                $info1[0]->payment_method             = 6;
                $info1[0]->payment_confirm            = 0;
                $info1[0]->note_pay                   = 'Chứng từ này sao chép từ chứng từ số '.$params;
                
                unset($info1[0]->id);
                $voucher_id = $this->voucher_model->create($info1[0]);
                
                //insert chứng từ công nợ phát sinh
                /*$this->view_data["voucherDebts"]                            = new stdClass();
                $this->view_data["voucherDebts"]->voucher_id                = $voucher_id;
                $this->view_data["voucherDebts"]->note                      = $info1[0]->note_pay ;
                $this->view_data["voucherDebts"]->customerID                = $info1[0]->customerID ;
                $this->view_data["voucherDebts"]->surplus                   = $info1[0]->surplus;
                $this->view_data["voucherDebts"]->amount                    = $info1[0]->real_fare;
                $this->view_data["voucherDebts"]->residual                  = $info1[0]->residual;
                $this->view_data["voucherDebts"]->payment_confirm           = 1;
                $this->view_data["voucherDebts"]->owner                     = $this->session->userdata['user_id'];
                $this->view_data["voucherDebts"]->agent_code                = $this->session->userdata['agent_code'];
                $this->view_data["voucherDebts"]->lastupdated               = time();

                $this->voucherDebts_model->create($this->view_data["voucherDebts"]);
                unset($this->view_data["voucherDebts"]);*/
            }
        }
        
        public function quickVoucher(){
            $id = json_decode($this->input->get("id"));
            if($id){
                $this->load->model('listcustomers_model');
                $id = explode(",",$id);
                $sumNet = $sumSale = 0;
                foreach($id as $key => $val){
                    $info           = $this->booking_model->find_by(array('id'=>$val));
                    $contact        = $this->listcustomers_model->find_by(array('customerID'=>$info[0]->customerID));
                    $phone          = json_decode($contact[0]->phone);
                    $customerID     = $contact[0]->customerID;
                    $booking_info[$key]   = array(
                        'booking_types'         =>      $info[0]->booking_types,
                        'airline'               =>      $info[0]->airline,
                        'booking_place_code'    =>      $info[0]->booking_place_code,
                        'createdTime'           =>      $info[0]->createdTime,
                        'net_fare_fake'         =>      $info[0]->net_fare,
                        'net_fare'              =>      number_format($info[0]->net_fare,"0",",",","),
                        'sale_fare_fake'        =>      $info[0]->sale_fare,
                        'sale_fare'             =>      number_format($info[0]->sale_fare,"0",",",",")
                    );
                    $sumNet     += $info[0]->net_fare;
                    $sumSale    += $info[0]->sale_fare;
                }
                
                $this->view_data['voucher']                     = new stdClass();
                $this->view_data['voucher']->phone              = $phone[0];
                $this->view_data['voucher']->customerID         = $customerID;
                $this->view_data['voucher']->booking_info       = $booking_info;
                $this->view_data['voucher']->sumNet             = $sumNet;
                $this->view_data['voucher']->sumSale            = $sumSale;
                $this->view_data['voucher']->length             = count($booking_info);

                $this->load->view('auth/voucher/quickVoucher', $this->view_data);
            }
        }
        
        public function delete(){
            if($this->input->server('REQUEST_METHOD')=='POST'){
                $voucher_query          =   $this->voucher_model->find_by(array('id' => $this->input->post('id')));
                $booking                =   $this->booking_model->find_by(array('voucher_id'=>$voucher_query[0]->id));
                
                foreach($booking as $value){
                    $updateBk                       =   new stdClass();
                    $updateBk->voucher_id           =   NULL;
                    $updateBk->payment_method       =   0;
                    
                    $this->booking_model->update($updateBk,$value->id);
                    
                    unset($updateBk);
                }

                $this->voucher_model->delete(array('id' => $this->input->post('id')));
                $this->session->set_flashdata('flash_message', $this->lang->line('delete_successful'));
                
                $c_session  =   '[DeleteCT]--';
                
                $paramAdminLog  = array(
                    'userid'            => $this->session->userdata['user_id'],
                    'lastLogin'         => date('Y-m-d :H:i:s',time()),
                    'ip'                => $_SERVER['REMOTE_ADDR'],
                    'logAction'         => $c_session.$voucher_query[0]->airline.'--'.$voucher_query[0]->booking_place_code.'--'.$this->input->post('deletebk'),
                    'agent_code'        => $this->session->userdata['agent_code']
                );

                $this->user_model->insertUserAdminLog($paramAdminLog);
                die("0");
            }
            $this->view_data['id']              =   $this->input->get('id');
            $this->view_data['session']         =   $this->input->get('session');
            $this->load->view('auth/voucher/delete', $this->view_data);
        }
}